﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace AoYing_DeviceCollection
{
    public class LogHelper
    {
        private readonly string fileFullName = string.Empty;
        public LogHelper()
        {
            var path = Environment.CurrentDirectory;
            var logPath = path + $"\\{DateTime.Now.Year}logs" + $"\\{DateTime.Now.Month}";
            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }

            fileFullName = logPath + "\\" + DateTime.Now.ToString("M") + ".txt";

            if (!File.Exists(fileFullName))
            {
                File.Create(fileFullName).Close();
            }

        }

        /// <summary>
        /// 正常记录用
        /// </summary>
        /// <param name="message"></param>
        public void Info(string message)
        {
            FileStream f = new FileStream(fileFullName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

            if (f.Length > 1024 * 1024 * 100) //文件如果超过100M,清空再记录
            {
                File.WriteAllText(fileFullName, string.Empty);
            }

            //向txt中写数据
            using (StreamWriter writer = new StreamWriter(f))
            {
                string writeDone = $"***************************************\r\n" +
                    $"Info:{DateTime.Now}-{message}" +
                    $"\r\n**************************************";
                writer.WriteLine(writeDone);
            }

            f.Close();
        }

        /// <summary>
        /// 写入异常信息用
        /// </summary>
        /// <param name="message"></param>
        public void Error(string message)
        {
            FileStream f = new FileStream(fileFullName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

            if (f.Length > 1024 * 1024 * 100) //文件如果超过100M,清空再记录
            {
                File.WriteAllText(fileFullName, string.Empty);
            }

            //向txt中写数据
            using (StreamWriter writer = new StreamWriter(f))
            {
                string writeDone = $"*****************************\r\n" +
                    $"Error:{DateTime.Now}-{message}" +
                    $"\r\n************************************";
                writer.WriteLine(writeDone);
            }

            f.Close();
        }

    }
}
